const CACHE_NAME = 'ai-human-models-v1';
const MODEL_CACHE_NAME = 'ai-human-models-cache';

// 模型文件URL模式
const MODEL_URL_PATTERNS = [
  /aiimg\.huilan\.com\/material\/model\/bucket-\d+\/.*\.(glb|gltf)$/i,
  /\.glb$/i,
  /\.gltf$/i,
  /\.hdr$/i
];

// 安装Service Worker并预缓存关键资源
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      console.log('AI Human Models Service Worker installed');
      return Promise.resolve();
    })
  );
  self.skipWaiting();
});

// 激活Service Worker并清理旧缓存
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames
          .filter((cacheName) => cacheName !== CACHE_NAME && cacheName !== MODEL_CACHE_NAME)
          .map((cacheName) => caches.delete(cacheName))
      );
    })
  );
  self.clients.claim();
});

// 拦截网络请求
self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);
  
  // 检查URL scheme是否支持缓存
  const supportedSchemes = ['http:', 'https:'];
  if (!supportedSchemes.includes(url.protocol)) {
    // 对于不支持的scheme（如chrome-extension:），直接返回网络请求
    return;
  }

  
  // 检查是否是模型文件（仅限GET请求）
  const isModelFile = request.method === 'GET' && MODEL_URL_PATTERNS.some(pattern => pattern.test(url.href));
  
  // 检查是否是 JS 文件
  const isJsFile = request.method === 'GET' && url.pathname.endsWith('.js');
  
  if (isModelFile) {
    // 对模型文件使用缓存优先策略
    event.respondWith(cacheFirst(request));
  } else if (isJsFile) {
    // 对 JS 文件使用网络优先策略（确保更新及时）
    event.respondWith(networkFirst(request));
  } else {
    return;
  }
});

// 缓存优先策略 - 用于模型文件
async function cacheFirst(request) {
  const cache = await caches.open(MODEL_CACHE_NAME);
  
  // 首先从缓存中获取
  const cachedResponse = await cache.match(request);
  if (cachedResponse) {
    console.log('Model served from cache:', request.url);
    return cachedResponse;
  }
  
  try {
    // 检查是否正在下载中
    const downloadingKey = `downloading_${request.url}`;
    if (self[downloadingKey]) {
      // 等待之前的下载完成
      await new Promise(resolve => {
        const checkInterval = setInterval(() => {
          if (!self[downloadingKey]) {
            clearInterval(checkInterval);
            resolve();
          }
        }, 100);
      });
      
      // 再次检查缓存
      const cached = await cache.match(request);
      if (cached) return cached;
    }
    
    // 标记为正在下载
    self[downloadingKey] = true;
    
    try {
      // 缓存中没有，从网络获取
      const networkResponse = await fetch(request);
      
      if (networkResponse.ok && request.method === 'GET') {
        // 检查URL scheme是否支持缓存
        const url = new URL(request.url);
        const supportedSchemes = ['http:', 'https:'];
        
        if (supportedSchemes.includes(url.protocol)) {
          // 检查是否已经缓存（防止并发写入）
          const doubleCheck = await cache.match(request);
          if (!doubleCheck) {
            // 将响应克隆并缓存
            const responseClone = networkResponse.clone();
            await cache.put(request, responseClone);
            console.log('Model cached:', request.url);
          }
        } else {
          console.log('Skipping cache for unsupported scheme:', url.protocol, request.url);
        }
      } else if (request.method !== 'GET') {
    console.log('Resource served from network:', request.url);
      }
      
      return networkResponse;
    } finally {
      // 清除下载标记
      delete self[downloadingKey];
    }
  } catch (error) {
    console.error('Failed to fetch model:', request.url, error);
    throw error;
  }
}

// 网络优先策略 - 用于其他资源
async function networkFirst(request) {
  const cache = await caches.open(CACHE_NAME);
  
  try {
    const networkResponse = await fetch(request);
    
    // if (networkResponse.ok && request.method === 'GET') {
    //   // 检查URL scheme是否支持缓存
    //   // const url = new URL(request.url);
    //   // const supportedSchemes = ['http:', 'https:'];
      
    //   // if (supportedSchemes.includes(url.protocol)) {
    //   //   // 缓存成功的响应
    //   //   const responseClone = networkResponse.clone();
    //   //   await cache.put(request, responseClone);
    //   // } else {
    //   //   console.log('Skipping cache for unsupported scheme:', url.protocol, request.url);
    //   // }
    // } else if (request.method !== 'GET') {
    //   console.log('Skipping cache for non-GET request:', request.method, request.url);
    // }
    console.log('Skipping cache for non-GET request:', request.method, request.url);
    
    return networkResponse;
  } catch (error) {
    // 网络失败，尝试从缓存获取
    const cachedResponse = await cache.match(request);
    if (cachedResponse) {
      return cachedResponse;
    }
    
    throw error;
  }
}

// 清理特定模型的缓存
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'CLEAR_MODEL_CACHE') {
    const modelUrl = event.data.url;
    if (modelUrl) {
      caches.open(MODEL_CACHE_NAME).then((cache) => {
        cache.delete(modelUrl);
        console.log('Model cache cleared:', modelUrl);
      });
    }
  }
  
  if (event.data && event.data.type === 'CLEAR_ALL_MODELS_CACHE') {
    caches.delete(MODEL_CACHE_NAME).then(() => {
      console.log('All models cache cleared');
    });
  }
});

// 定期清理过期缓存
self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'clean-old-models') {
    event.waitUntil(cleanOldModels());
  }
});

async function cleanOldModels() {
  const cache = await caches.open(MODEL_CACHE_NAME);
  const keys = await cache.keys();
  
  // 这里可以添加过期时间逻辑
  // 例如：删除超过30天的缓存
  const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000);
  
  keys.forEach(async (request) => {
    const response = await cache.match(request);
    if (response) {
      const dateHeader = response.headers.get('date');
      if (dateHeader) {
        const responseDate = new Date(dateHeader);
        if (responseDate.getTime() < thirtyDaysAgo) {
          cache.delete(request);
          console.log('Old model cache cleaned:', request.url);
        }
      }
    }
  });
}